var name = 'undefine';

var subSocket = new WebSocket("ws://192.168.2.101:1923/");

$(document).ready(function(){
	init();
});

function init(){
	name = "u" + (Math.random() + "").substring(2, 5);
	document.getElementById("userName").value = name;
}

subSocket.onopen = function() {
	subSocket.send(JSON.stringify({
		"action" : 'join',
		"name" : name
	}));
};

subSocket.onclose = function() {
	subSocket.send(JSON.stringify({
		"action" : 'logout',
		"name" : name
	}));
};

subSocket.onmessage = function(event) {
	var data = JSON.parse(event.data);
	if (data.action == 'join') {
		$("#msgs").append("<div class='join'><b>" + data.name + "</b> joined</div>");
	} else if (data.action == 'logout') {
		$("#msgs").append("<div class='logout'><b>" + data.name + "</b> logout</div>");
	} else if (data.action == 'msg') {
		$("#msgs").append("<div class='msg'><b>" + data.name + ": </b>" + data.data + "</div>");
	}
};

function sub(){
	var msg = document.getElementById("in").value;
	subSocket.send(JSON.stringify({
		"action" : 'msg',
		"name" : name,
		"data" : msg
	}));
}

function leave(){
	subSocket.send(JSON.stringify({
		"action" : 'logout',
		"name" : name
	}));
	subSocket.close();
}

window.onbeforeunload(function(){ subSocket.close();});
 